//
// Created by firear on 2/18/20.
//

#include <unistd.h>
#include "MyTcpClient.h"
#include "firear_rpc_NetHelper.h"
#include "../frpc/tcpclient.h"
#include "../frpc/rpchead.h"

#define LOG_TAG "mytcpclient"
#include "../frpc/publicfun/debug.h"


class MyTcpClient:public TcpClient{
public:
    int on_connect(int status){
        LOGD("%s: %d", __func__, status);
        return 0;
    }

    int deal(RpcProtHead *msg){
        LOGD("%s: %s", __func__, msg->data.c_str());
        return 0;
    }
};


MyTcpClient g_mytcpclient;


extern "C" {
jint Java_firear_rpc_NetHelper_connectToServer(JNIEnv *env, jclass obj, jstring ip, jint port)
{
    const char * _ip = env->GetStringUTFChars(ip, NULL );
    g_mytcpclient.connectToServer(_ip, port);
    env->ReleaseStringUTFChars(ip , _ip);
    return 0;
}


jint Java_firear_rpc_NetHelper_sendToServer(JNIEnv *env, jclass obj, jbyteArray data)
{
    jbyte * _data = env->GetByteArrayElements( data, NULL );
    jsize datalen = env->GetArrayLength(data);

    g_mytcpclient.send_to_server((const char *)_data, (size_t)datalen);

    env->ReleaseByteArrayElements(data , _data , 0 );
    return 0;
}
}
//
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {

    // LOGI("!!!!!!!!\n");

    JNIEnv *env = NULL;
    jint result = -1;

    //
    if (vm->GetEnv((void **) &env, JNI_VERSION_1_4) != JNI_OK) {
        // LOGI("GetEnv failed!\n");
        return result;
    }

    return JNI_VERSION_1_4;
}

